<template>
  <div class="site-data-list">
    <div class="site-data-list__header g-flex-between-center" v-if="!props.readonly">
      <div class="header__left g-flex-start-center">
        <el-button class="g-mr12" type="primary" @click="handleAdd" v-if="!props.readonly"
          ><CIcon class="g-mr4" type="c-xian-xinjian"></CIcon>新增场地数据</el-button
        >
        <CFileUploadAndTempDownload
          :uploadApi="importBomFieldData"
          :params="{ formNo }"
          @success="handleRefresh"
          :templateUrl="commonConfig.SUPPLIER_SITE_DATA_TEMPLATE_URL"
          uploadText="批量导入"
          v-if="!props.readonly"
        />
      </div>
      <div class="header__right">
        <div class="header__right-label"
          >以下数据对应的零部件数量 <span class="header__right-label--required">*</span></div
        >
        <CDosageAndUnit
          class="header__right-input"
          v-model:dosage="headerRightFormState.productNum"
          v-model:unit="headerRightFormState.productUnit"
          placeholder="请输入"
          is-group
          unit-type="ALL"
          :clearable="false"
          :disabled="props.readonly"
          @change-dosage="editProductNumReq"
          @change-unit="editProductUnitReq"
          v-loading="productNumLoading"
        ></CDosageAndUnit>
      </div>
    </div>
    <CTable
      ref="tableRef"
      rowKey="nodeNo"
      :loadData="loadData"
      :tableFieldsSetting="tableFieldsSetting"
      :extraTableOption="extraTableOption"
      :pagination="false"
      border
    >
      <template #dataTypeSlot="{ scope }">
        {{ flowDataTypeMap && scope.row.dataType ? flowDataTypeMap[scope.row.dataType] : '-' }}
      </template>
      <template #dosageSlot="{ scope }">
        <CTableEditCell
          v-model="scope.row.dosage"
          inputType="number"
          :tableRow="scope.row"
          trigger="click-cell"
          placeholder="请输入"
          showPlaceholderStyle
          :updateFn="handleDosageUpdate"
          :local-value-formatter="handleLocalValueFormatter"
          align="right"
          v-if="!props.readonly"
        ></CTableEditCell>
        <template v-else>
          {{ scope.row.dosage || '-' }}
        </template>
      </template>
      <template #weightSlot="{ scope }">
        <span v-if="isWeightUnit(scope.row.unit)">-</span>
        <span v-else>{{ scope.row.weight ? scope.row.weight + scope.row.weightUnit : '-' }}</span>
      </template>
      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)"></CTableButtonGroup>
      </template>
    </CTable>
    <FlowDialog
      v-model:visible="dialogVisible"
      :flowItem="tempProcessItem"
      :processNo="tempProcessNo"
      :formNo="formNo"
      :nodeNo="tempNodeNo"
      @refresh="handleRefresh"
    ></FlowDialog>
    <MaterialDialog
      v-model:visible="materialDialogVisible"
      :nodeNo="tempNodeNo"
      :formNo="formNo"
      :read-only="props.readonly"
      @refresh="handleRefresh"
    ></MaterialDialog>
  </div>
</template>

<script lang="ts" setup name="SiteDataList">
import { withDefaults, defineProps, ref, defineExpose } from 'vue';
import { useMessage } from '@/hooks/useMessage';
import { CTable } from '@/components/CTable';
import type { TableFieldsSettingType } from '@/components/CPageTable';
import { isWeightUnit } from '@/utils';
import { FlowDialog } from './components/FlowDialog';
import MaterialDialog from './components/materialDialog/index.vue';
import CFileUploadAndTempDownload from '@/businessComponents/CFileUploadAndTempDownload/index.vue';
import CDosageAndUnit from '@/businessComponents/CDosageAndUnit/index.vue';
import type { ProcessDataItem } from '@/apis/pcf/myModel/model/modelDetailModel';
import {
  importBomFieldData,
  getListManufacture,
  remoteManufactureData,
  editManufactureData
} from '@/apis/todo/flowBusiness';
import { CTableButtonGroup } from '@/components/CTable';
import type { TableButtonItem } from '@/components/CTable';
import { getSystemDict } from '@/apis/common/common';
import { uniqWith, isEqual } from 'lodash';
import { useEditProductNum } from './useEditProductNum';
import type { GetSupplierFormDetailResult } from '@/apis/supplier/model/supplierModel';
import { limitStrLength } from '@/utils';
import { CTableEditCell } from '@/components/CTableEditCell';
import commonConfig from '@/config';

interface SiteDataListProps {
  formNo: string;
  readonly?: boolean;
  supplierFormInfo?: GetSupplierFormDetailResult;
}

const props = withDefaults(defineProps<SiteDataListProps>(), {
  readonly: false
});
const { createMessage, createConfirm } = useMessage();

const { headerRightFormState, productNumLoading, editProductNumReq, editProductUnitReq } =
  useEditProductNum(props.formNo, props);

const tableFieldsSetting: TableFieldsSettingType[] = [
  {
    title: '名称',
    field: 'nodeName',
    minWidth: 200
  },
  {
    title: '类型',
    field: 'dataType',
    slot: 'dataTypeSlot',
    width: 150
  },
  {
    title: '用量',
    field: 'dosage',
    slot: 'dosageSlot',
    align: 'right',
    width: 100
  },
  {
    title: '单位',
    field: 'unit',
    width: 80
  },
  {
    title: '备注',
    field: 'remark',
    minWidth: 120
  },
  {
    title: '操作',
    field: 'op',
    slot: 'op',
    width: 220
  }
];

const extraTableOption = {
  scrollY: { enabled: true },
  maxHeight: '460px',
  rowConfig: { height: 44 }
};

const flowDataTypeMap = ref<Record<string, string>>({});
/**
 * 获取类型和名称 字典
 */
async function getTypeDict() {
  try {
    const res = await getSystemDict('FLOW');

    const uniqOpt = uniqWith(
      res.map(item => {
        return {
          label: item.dataDesc,
          value: item.dataGroup
        };
      }),
      isEqual
    );

    uniqOpt?.forEach(item => {
      flowDataTypeMap.value[item.value] = item.label;
    });
  } catch (error) {
    console.log('error', error);
  }
}

getTypeDict();

/**
 * 加载数据
 */
function loadData() {
  return getListManufacture(props.formNo).then(res => {
    return {
      records: res,
      total: res.length
    };
  });
}

const tableRef = ref();
/**
 * 刷新
 */
function handleRefresh() {
  tableRef.value?.refresh();
}

/**
 * 工序item的临时变量（用于编辑流/运输路径弹窗）
 */
const tempProcessItem = ref<ProcessDataItem>();

/**
 * 流/运输路径弹窗 processNo
 * 有值：新增
 * 无值：编辑
 */
const tempProcessNo = ref('');

/**
 * 流/运输路径弹窗 nodeNo
 * 有值：编辑
 * 无值：新增
 */
const tempNodeNo = ref('');

/**
 * 页面loading
 */
const loading = ref(false);

/**
 * 流弹窗 显示状态
 */
const dialogVisible = ref(false);

/**
 * 新增流/运输路径
 */
function handleAdd(processNo: string) {
  console.log('handleAdd', processNo);
  tempProcessItem.value = undefined;
  tempProcessNo.value = processNo;
  tempNodeNo.value = '';
  dialogVisible.value = true;
}

/**
 * 编辑流/运输路径
 */
function handleEdit(row: ProcessDataItem) {
  tempProcessItem.value = row;
  tempNodeNo.value = row.nodeNo;
  dialogVisible.value = true;
}

/**
 * 删除流/运输路径
 */
function handleDelete(nodeNo: string) {
  createConfirm('提示', '删除后不可恢复，是否继续？', {
    iconType: 'warning'
  }).then(async () => {
    try {
      loading.value = true;
      await remoteManufactureData(nodeNo);
      createMessage.success('删除成功！');
      handleRefresh();
      loading.value = false;
    } catch (error) {
      console.log('error', error);
      loading.value = false;
    }
  });
}
const materialDialogVisible = ref(false);
const handleMaterial = (row: ProcessDataItem) => {
  materialDialogVisible.value = true;
  tempNodeNo.value = row.nodeNo;
};

/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(row: ProcessDataItem): TableButtonItem[] {
  if (props.readonly) {
    return [
      {
        text: `数据佐证资料(${row.supplierFormAttachmentCount ?? 0})`,
        onClick: () => handleMaterial(row),
        disabled: !row.supplierFormAttachmentCount,
        style: !row.supplierFormAttachmentCount ? 'color: #96A7B3' : ''
      }
    ];
  } else {
    return [
      {
        text: '编辑',
        onClick: () => handleEdit(row)
      },
      {
        text: `数据佐证资料(${row.supplierFormAttachmentCount ?? 0})`,
        onClick: () => handleMaterial(row)
      },
      {
        text: '删除',
        onClick: () => handleDelete(row.nodeNo)
      }
    ];
  }
}

// localValue的格式化
function handleLocalValueFormatter(value: string) {
  return limitStrLength(String(value), 9, true);
}

// 用量更新操作
async function handleDosageUpdate(value: any, row: ProcessDataItem): Promise<boolean> {
  console.log('value', value, row);
  if (!value && value !== 0) {
    createMessage.error('用量不能为空！');
    return Promise.reject(false);
  }
  try {
    const params = {
      ...row,
      dosage: value
    };
    await editManufactureData(params);
    createMessage.success('编辑用量成功！');
    return Promise.resolve(true);
  } catch (error) {
    return Promise.reject(false);
  }
}
defineExpose({
  headerRightFormState
});
</script>

<style lang="scss" scoped>
.site-data-list {
  :deep(.vxe-table) {
    .vxe-tree--btn-wrapper {
      top: 10px;
      .vxe-tree--node-btn {
        color: #435970 !important;
      }
    }
  }
}

.site-data-list__header {
  // height: 48px;
  padding-bottom: 16px;
  .header__right {
    display: flex;
    align-items: center;
    flex-shrink: 0;

    :deep(.el-input-group__append) {
      // background-color: #fff;
      .el-input {
        border: none;
      }
    }
    .header__right-label {
      margin-right: 12px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #0a1f33;
      line-height: 22px;
      .header__right-label--required {
        color: #ff4829;
      }
    }
    .header__right-input {
      width: 300px;
      :deep(.el-input-group__append) {
        padding: 0;
        width: 120px;
      }
    }
  }
}
</style>
